package com.ksr.logistics.shiro;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyFormAuthenticationFilter extends FormAuthenticationFilter {

    //清除session中保存的url,第二次认证成功进入设定的successUrl
    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
        Session session=subject.getSession(false);
        if (session!=null){
            session.removeAttribute(WebUtils.SAVED_REQUEST_KEY);
        }
        return super.onLoginSuccess(token, subject, request, response);
    }


    //设置"记住我"后（从记住我的Cookie中获取主体的身份）
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        Subject subject=getSubject(request, response);
        Session session=subject.getSession();
        if (!subject.isAuthenticated() && subject.isRemembered()){
            Object principal = subject.getPrincipal();
            session.setAttribute("admin", principal);
        }

        return subject.isAuthenticated() || subject.isRemembered();
    }


    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        String verifyCode = request.getParameter("verifyCode");
        HttpServletRequest req=(HttpServletRequest) request;
        if (StringUtils.isNotBlank(verifyCode)){
            String code =(String) req.getSession().getAttribute("rand");
            if (!verifyCode.equalsIgnoreCase(code)){
                req.setAttribute("errorMsg","验证码错误,请重试");
                req.getRequestDispatcher("/login.jsp").forward(request,response);
                return false;
            }
        }else {
            if ("/logistics/admin/login".equals(req.getRequestURI()) || "/logistics/login.jsp".equals(req.getRequestURI())){
                req.setAttribute("errorMsg","验证码不能为空,请重试");
                req.getRequestDispatcher("/login.jsp").forward(request,response);
                return false;
            }
        }

        return super.onAccessDenied(request, response, mappedValue);
    }

    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        Subject subject = getSubject(request, response);
        if (subject.isAuthenticated() || subject.isRemembered()){
            HttpServletRequest req = (HttpServletRequest) request;
            if ("/logistics/admin/login".equals(req.getRequestURI())){
                HttpServletResponse resp=(HttpServletResponse)response;
                try {
                    resp.sendRedirect("/logistics/index/main");
                } catch (Exception e){
                }
            }
        }
        return super.preHandle(request, response);
    }
}
